/**
 * Created by willem
 */
import './index.scss';
import { Component } from 'react';
import T from 'utils/T';

import {
    EnumMarkerPosition,
    EnumPath,
    EnumLevel,
    EnumLiveIndex
} from './EnumCommon';
import CarouselRight from './carouselRight';
import TextCarousel from './textCarousel';

import redDot from './img/redDot.svg';
import cityImg from './img/cityImg.png';
import defaultFigure from './img/defaultFigure.png';
import ReactEcharts from 'echarts-for-react';

export default class CarouselGather extends Component {
    constructor(props) {
        super(props);
        this.state = {
            cityData: {
                stationID: '中国-重庆',
                weather: '多云',
                icon: '',
                TEMP: '16 ~ 27℃',
                cityImg: cityImg
            },
            liveIndex: EnumLiveIndex,
            serviceData: [
                {
                    name: '能源',
                    list: '交通运输部路网中心,海上搜救中心,公安部交通管理局,外交部礼宾司,交通运输部路网中心,公安部交通管理局公路刑警处,交通运输部路网中心,安部交通管理局公路刑警处'
                },
                {
                    name: '环境',
                    list: '交通运输部路网中心,公安部交通管理局公路刑警处,国家旅游局全国假日旅游部际协调会议办公室,中石油交通预报'
                },
                {
                    name: '保险',
                    list: '新能源行业,交通运输部路网中心,公安部交通管理局公路刑警处'
                },
                {
                    name: '农林',
                    list: '交通运输部路网中心,海上搜救中心,公安部交通管理局,外交部礼宾司,交通运输部路网中心'
                },
                {
                    name: '应急',
                    list: '新能源行业,交通运输部路网中心,公安部交通管理局公路刑警处'
                },
                {
                    name: '电力',
                    list: '新能源行业,海上搜救中心,公安部交通管理局,外交部礼宾司,交通运输部路网中心'
                },
            ]

        };
        this.timer = null;
        this.CarouselRight = null;
        this.TextCarousel = null;
        this.svgTimer = null;
    }

    componentDidMount() {
        this.initData();
        // 定时刷新
        this.updateData();
        this.updateMarker();

        this.timer = setInterval(() => {
            this.updateData();
        }, 1000 * 3600);

    }

    /**
     * 第一次更新数据
     */
    initData = () => {
        this.setMarker();
        this.boxCarousel(this.carouselLeftBox);
        this.boxCarousel(this.carouselRightBox);
        this.drawCarouselRight(this.state.serviceData);


    };



    /**
     * 更新数据
     */
    updateData = () => {

    };

    /**
     * 更新内容
     * @returns {Array}
     */
    updateMarker = () => {
        let i = 0;
        this.updateCityData(0);
        this.svgTimer = setInterval(() => {
            i++;
            this.updateCityData(i);
            if (i >= EnumPath.length) {
                i = 0;
                this.setMarker();
            }

        }, 5 * 1000);

    };

    updateCityData = (i) => {
        this.setState({
            cityData: {
                stationID: '中国-重庆',
                weather: '多云' + Math.round(Math.random() * 40),
                icon: '',
                TEMP: '16 ~ 27℃',
                cityImg: cityImg
            },
        });
    };

    /**
     * 设置svg动画
     */
    setMarker = () => {
        let paths = '';
        EnumPath.forEach((item, index) => {
            paths += `<path d="${item.path}" stroke="rgba(0,0,0,0)" fill="none" id="${'path' + index}" fill-opacity="0"/>`;
        });

        $(this.svgBox).html(`<svg>
            ${paths}
            <image xlink:href="${redDot}" x="-20" y="-15" height="30" width="40" id="marker"/>

            <animateMotion id="firstAnimate" xlink:href="#marker" dur="5s" begin="0" fill="remove" rotate="auto">
                <mpath xlink:href="#path0"/>
            </animateMotion>
            <animateMotion  xlink:href="#marker" dur="5s" begin="firstAnimate.begin + 5s" fill="remove" rotate="auto">
                <mpath xlink:href="#path1"/>
            </animateMotion>
            <animateMotion  xlink:href="#marker" dur="5s" begin="firstAnimate.begin + 10s" fill="remove" rotate="auto">
                <mpath xlink:href="#path2"/>
            </animateMotion>
            <animateMotion  xlink:href="#marker" dur="5s" begin="firstAnimate.begin + 15s" fill="remove" rotate="auto">
                <mpath xlink:href="#path3"/>
            </animateMotion>
            <animateMotion  xlink:href="#marker" dur="5s" begin="firstAnimate.begin + 20s" fill="remove" rotate="auto">
                <mpath xlink:href="#path4"/>
            </animateMotion>
            <animateMotion  xlink:href="#marker" dur="5s" begin="firstAnimate.begin + 25s" fill="remove" rotate="auto">
                <mpath xlink:href="#path5"/>
            </animateMotion>
            <animateMotion  xlink:href="#marker" dur="5s" begin="firstAnimate.begin + 30s" fill="remove" rotate="auto">
                <mpath xlink:href="#path6"/>
            </animateMotion>
            <animateMotion  xlink:href="#marker" dur="5s" begin="firstAnimate.begin + 35s" fill="freeze" rotate="auto">
                <mpath xlink:href="#path7"/>
            </animateMotion>

        </svg>`);
    };


    /**
     * 添加地图文字
     * @returns {Array}
     */
    getMapMarker = () => {
        let lis = [];
        T.lodash.forEach(EnumMarkerPosition, (v, k) => {
            lis.push(<li key={k} style={{ left: v.position[0], top: v.position[1] }}>
                <span>{v.name}</span>
            </li>);
        });
        return lis;
    };

    /**
     * 环形图配置
     * @param level
     * @param type
     * @returns {{title: {show: boolean}, grid: {left: number, top: number, bottom: number, right: number}, series: {name: string, type: string, radius: string[], avoidLabelOverlap: boolean, label: {normal: {show: boolean, position: string, formatter: *}, emphasis: {show: boolean}}, labelLine: {normal: {show: boolean}}, data: *[]}[]}}
     */
    getOption = (level, type = 'left') => {

        const colors = {
            left: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                    { offset: 0, color: '#E4FF33' },
                    { offset: 1, color: '#FF4CFF' }
                ]
            },
            right: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                    { offset: 0, color: '#00EFFF' },
                    { offset: 1, color: '#0781FA' }
                ]
            }
        };

        return {
            title: {
                show: false
            },
            grid: {
                left: 0,
                top: 0,
                bottom: 0,
                right: 0
            },
            series: [{
                name: '等级',
                type: 'pie',
                radius: ['82%', '90%'],
                avoidLabelOverlap: false,
                label: {
                    normal: {
                        show: true,
                        position: 'center',
                        formatter: EnumLevel[level]
                    },
                    emphasis: {
                        show: true
                    }
                },
                labelLine: {
                    normal: {
                        show: false
                    }
                },
                data: [{
                    name: 'shadow',
                    value: 100 - level * 20,
                    clockwise: true,
                    label: {
                        normal: {
                            show: false,
                            fontSize: 0
                        }
                    },
                    itemStyle: {
                        normal: {
                            borderColor: '#1c366e',
                            borderWidth: 8

                        },
                        emphasis: {
                            color: '#193776'
                        }
                    },
                    hoverAnimation: false
                }, {
                    name: 'level',
                    value: level * 20,
                    clockwise: true,
                    label: {
                        normal: {
                            fontSize: 20,
                            color: '#FFFFFF',
                            fontWeight: 'bolder'
                        }
                    },
                    hoverAnimation: false,
                    itemStyle: {
                        normal: {
                            borderColor: colors[type],
                            borderWidth: 8
                        }
                    }
                }]
            }]
        };
    };


    /**
     * 生活指标轮播盒子
     * @param ele
     */
    boxCarousel = (ele) => {

        const $box = $(ele);

        const items = $box.find('.outerBox'); // 轮播循环体
        const width = items.first().width();

        const itemsLen = items.length;

        let interval = 4000; // interval 自动轮播间隔时间
        let autoPlay = true; // autoPlay 是否开启自动轮播
        let run = null;
        let i = 0;

        autoPlay && auto();
        function auto() {
            run = setInterval(function () {
                i++;
                if (i === itemsLen) {
                    $box.css({
                        left: 0
                    });
                    i = 1;
                }
                move();
            }, interval);
        }
        function move() {
            $box.stop().animate({
                left: -width * i
            }, 300, 'swing');
        }

    };

    // 获取生活指标dom
    getCarouselBox = (data, type) => {

        data = data.concat(data[0]);
        return data.map((item, index) => {
            return <li className={'outerBox'} key={index}>
                <div className={'title'}>{item.category}</div>
                <div className={'content'}>
                    <div className={'innerBox'}>
                        <img src={item.img} alt="" height="260" />
                        <div>
                            <div>
                                <ReactEcharts
                                    option={this.getOption(EnumLevel[item.level], type)}
                                    notMerge={true}
                                    lazyUpdate={true}
                                    style={{
                                        width: 166,
                                        height: 166
                                    }}
                                />
                                {/* <p>{item.msg}</p> */}
                            </div>

                        </div>
                    </div>

                </div>
            </li>;
        });
    }

    /**
     * 绘制双中心3d轮播图
     * @param data
     */
    drawCarouselRight(data) {
        if (this.CarouselRight) clearInterval(this.CarouselRight.timer);
        this.CarouselRight = new CarouselRight($(this.carouselRightBox), {
            curDisplay: 0,
            autoPlay: true,
            interval: 6000,
            data
        }, (curDisplay) => {
            const index = curDisplay % data.length;
            if (this.TextCarousel) clearInterval(this.TextCarousel.timer);
            this.TextCarousel = new TextCarousel($(this.listBox), {
                curDisplay: 0,
                autoPlay: true,
                interval: 3000, // 毫秒单位
                boxName: 'listInner',
                itemName: 'item',
                data: data[index].list.split(',')
            });
        });
    }



    componentWillUnmount() {
        clearInterval([this.timer, this.svgTimer, this.TextCarousel, this.CarouselRight]);
    }



    render() {
        const { cityData } = this.state;
        return (<div className={'zhitianBox'}>
            <div className={'content'}>
                <div className={'mapImgBox'}>
                    <div className={'content'}>
                        <div className={'titleTop'}>丝绸之路经济带</div>
                        <div className={'titleBot'}>21世纪海上丝绸之路</div>
                        <ul className={'positions'}>
                            {this.getMapMarker()}
                        </ul>

                        <div className={'svgBox'} ref={e => this.svgBox = e} />

                        <div className={'cityDetails'}>
                            <div>
                                <span>{cityData.stationID}</span>
                                <div>
                                    <div>
                                        <img src={cityData.icon} alt="" />
                                        <span>{cityData.weather}</span>
                                    </div>
                                    <p>{cityData.TEMP}</p>
                                </div>
                            </div>
                            <div style={{
                                background: 'url(' + cityData.cityImg + ') no-repeat center center',
                            }}
                            />

                        </div>
                    </div>
                </div>
                <div className={'line'} />

                <div className={'liveIndexBox'}>
                    <div>
                        <ul className={'carouselBox'} ref={e => (this.carouselLeftBox = e)} >
                            {this.getCarouselBox(T.lodash.take(this.state.liveIndex, 6))}
                        </ul>
                    </div>

                </div>
                <div className={'liveIndexBox'}>
                    <div>
                        <ul className={'carouselBox'} ref={e => (this.carouselRightBox = e)} >
                            {this.getCarouselBox(T.lodash.takeRight(this.state.liveIndex, 6), 'right')}
                        </ul>
                    </div>
                </div>



                <div className={'carouselBox'} />

                <div className={'serviceBox'}>
                    <div className={'content'}>
                        <div className={'title'}>服务用户</div>
                        <ul className={'titleBox'}>
                            <li><span>蓝天<br />行动</span></li>
                            <li><span>三农<br />服务</span></li>
                            <li><span>军民<br />融合</span></li>
                            <li><span>脱贫<br />攻坚</span></li>
                            <li><span>长江<br />经济带</span></li>
                        </ul>
                        <div className={'carouselRight_box'} ref={e => (this.carouselRightBox = e)} />
                        <div className={'listBox'}>
                            <div className={'listOuter'} ref={e => this.listBox = e}>

                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>);
    }
}

